//
//  DSPStatusPictureView.swift
//  SWweibo
//
//  Created by 杜守鹏 on 16/1/5.
//  Copyright © 2016年 杜守鹏. All rights reserved.
//

import UIKit

// 配图视图里面最大的列数
let DSPStatusPictureMaxCol = 3
// 每一个条目之前的间距
private let itemMargin: CGFloat = 5
// 每一个条目的宽度以及高度

private let cellID = "picViewCell"
private let itemWH = (SCREENWIDTH - 2 * DSPStatusCellMargin - 2 * itemMargin) / CGFloat(DSPStatusPictureMaxCol)


class DSPStatusPictureView: UICollectionView,UICollectionViewDataSource {
      // 定义属性，供外界设置数据
    var picUrls: [DSPStatusPictureInfo]? {
        didSet{
            // 取出数量
            let count = picUrls?.count ?? 0
//            // 显示有多少张图片
//            countLabel.text = "\(count)"
            
//             根据有多少张图片去更新大小约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(calcViewSize(count))
            }
            reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
      dataSource = self
       registerClass(DSPStatusPictureViewCell.self, forCellWithReuseIdentifier: cellID)
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    
    /// 根据图片的张数，计算当前配图视图的大小
    private func calcViewSize(count: Int) -> CGSize {

        // 计算列数
        var col = count > DSPStatusPictureMaxCol ? DSPStatusPictureMaxCol : count
        // 如果是4张图片，显示两列
        if count == 4 {
            col = 2
        }
 
        let row = (count - 1) / DSPStatusPictureMaxCol + 1
        
        
        // 计算宽度以及高度
        let width = CGFloat(col) * itemWH + CGFloat(col - 1) * itemMargin
        let height = CGFloat(row) * itemWH + CGFloat(row - 1) * itemMargin
        
        // 返回结果
        return CGSize(width: width, height: height)
    }
    // MARK: - 懒加载控件
    
    // 作测试用，显示当前配图控件里面要显示多少张图片
    private lazy var countLabel: UILabel = {
        let label = UILabel(textColor: UIColor.blackColor(), fontSize: 35)
        return label
    }()
    
}
//数据源方法
extension DSPStatusPictureView{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return picUrls?.count ?? 0
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! DSPStatusPictureViewCell
        cell.picUrl = picUrls![indexPath.item]
        return cell       
    }
}

//自定义cell
class DSPStatusPictureViewCell : UICollectionViewCell{
    var picUrl:DSPStatusPictureInfo?{
        didSet{
            if let urlString = picUrl?.thumbnail_pic{
                let url = NSURL(string: urlString)
                imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        addSubview(imageView)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }
    
    //MARK:懒加载ImageView
    private lazy var imageView : UIImageView = {
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        view.contentMode = .ScaleAspectFill
        view.clipsToBounds = true
        
        return view
    }()
    
}